/**
 * 开发相关函数
 * Created by fanGe on 2019-02-21 09:44:57.
 * 自动生成
 */
import store from '@/store'

/**
 * 字段类型映射控件类型
 * @type {{char: string, varchar: string, nvarchar: string, tinytext: string, mediumtext: string, text: string, longtext: string, tinyblob: string, mediumblob: string, blob: string, longblob: string, tinyint: string, smallint: string, mediumint: string, int: string, integer: string, bigint: string, float: string, double: string, decimal: string, date: string, time: string, datetime: string, timestamp: string, year: string}}
 */
export const COMPONENT_MAP = {
  'char': 'text',
  'varchar': 'text',
  'nvarchar': 'text',
  'tinytext': 'text',
  'mediumtext': 'textArea',
  'text': 'textArea',
  'longtext': 'textArea',
  'tinyblob': 'upload',
  'mediumblob': 'upload',
  'blob': 'upload',
  'longblob': 'upload',
  'tinyint': 'number',
  'smallint': 'number',
  'mediumint': 'number',
  'int': 'number',
  'number': 'number',
  'integer': 'number',
  'bigint': 'number',
  'float': 'decimal',
  'double': 'decimal',
  'decimal': 'decimal',
  'date': 'date',
  'time': 'time',
  'datetime': 'datetime',
  'timestamp': 'timestamp',
  'year': 'year',
  'dict': 'dict',
  'user': 'user',
  'project': 'project',
  'datasource': 'datasource',
  'library': 'library',
  'version': 'version'
}

/**
* jAVA类型映射
* @type {{char: string, varchar: string, nvarchar: string, tinytext: string, mediumtext: string, text: string, longtext: string, tinyblob: string, mediumblob: string, blob: string, longblob: string, tinyint: string, smallint: string, mediumint: string, int: string, integer: string, bigint: string, float: string, double: string, decimal: string, date: string, time: string, datetime: string, timestamp: string, year: string}}
*/
export const JAVATYPE_MAP = {
  'char': 'Char',
  'varchar': 'String',
  'nvarchar': 'String',
  'tinytext': 'String',
  'mediumtext': 'String',
  'text': 'String',
  'longtext': 'String',
  'tinyblob': 'String',
  'mediumblob': 'String',
  'blob': 'String',
  'longblob': 'String',
  'tinyint': 'Int',
  'smallint': 'Int',
  'mediumint': 'Int',
  'number': 'Int',
  'int': 'Int',
  'integer': 'Int',
  'bigint': 'Long',
  'float': 'Float',
  'double': 'Double',
  'decimal': 'Float',
  'date': 'Date',
  'time': 'Date',
  'datetime': 'Date',
  'timestamp': 'Date',
  'year': 'Int',
  'dict': 'Dict',
  'user': 'User',
  'project': 'Project',
  'datasource': 'Datasource',
  'library': 'Library',
  'version': 'Version'
}

/**
 * 缓存对象
 * @type {null}
 */
var componentList = null

/**
 * 获取header方法
 * @returns {*} headers
 */
export function getHeaders () {
  return {
    Authorization: 'Bearer ' + store.getters.token,
    token: store.getters.token
  }
}

/**
 * 获取组件列表
 * @returns {Array} 组件列表
 */
export function getComponentList () {
  if (componentList && componentList.length > 0) {
    return componentList
  }
  let r = []
  for (let key in COMPONENT_MAP) {
    let t = COMPONENT_MAP[key]
    if (r.indexOf(t) === -1) {
      r.push(t)
    }
  }
  componentList = r
  return r
}

/**
 * 获取列显示组件
 * @param {Object} column 列信息
 * @param {String} dsType 数据库类型（TODO 后期如果需要区分不同数据库类型，这里扩展）
 * @returns {*} 格式化之后的值
 */
export function getColumnComponent (column, dsType) {
  if (!column || !column.type) {
    return 'input'
  }
  if (column.component) {
    return column.component
  }
  // 如果长度超长，则认为是多行文本
  if (column.type in ['nvarchar', 'varchar']) {
    return column.len > 255 ? 'textArea' : 'text'
  }
  return COMPONENT_MAP[column.type.toLowerCase()] || 'text'
}

/**
 * 获取列显示组件
 * @param {Object} column 列信息
 * @param {String} dsType 数据库类型（TODO 后期如果需要区分不同数据库类型，这里扩展）
 * @returns {*} 格式化之后的值
 */
export function getJavaType (column, dsType) {
  if (!column || !column.type) {
    return 'Any'
  }
  if (column.javaType && column.javaType !== 'Any') {
    return column.javaType
  }
  return JAVATYPE_MAP[column.type.toLowerCase()] || 'Any'
}

/**
 * 转换为驼峰命名法
 * @param {String} value 驼峰命名法
 * @returns {String} 驼峰字符串
 */
export function toCamelCase (value) {
  var re = /[-_](\w)/
  return value.replace(re, function ($0, $1) {
    return $1.toUpperCase()
  })
}

export function getUrlParams (url) {
  let paraIndex = url.indexOf('?')
  if (paraIndex === -1) {
    return null
  }
  let params = {}
  url = url.substr(paraIndex + 1, url.length)
  let paras = url.split('&')
  paras.forEach(element => {
    let para = element.split('=')
    params[para[0]] = decodeURIComponent(para[1])
  })
  return params
}

export function buildRouterMapping (mapping, r) {
  if (r.path.indexOf('/') !== 0) {
    mapping['/' + r.path] = r.name
  } else {
    mapping[r.path] = r.name
  }
  if (r.children !== undefined && r.children !== null && r.children.length > 0) {
    r.children.forEach(it => {
      buildRouterMapping(mapping, it)
    })
  }
}

/**
 * 获取字符串中的参数
 * @param {String} str 总字符串（'name1=xxx;name2=xxx'）
 * @param {String} name 要筛选的字段name1
 * @returns {string} 返回的字段xxx
 */
export function getPara (str, name) {
  // 查询检索的值
  let search = name + '='
  // 返回值
  let ret = ''
  if (str.length > 0) {
    let s = decodeURIComponent(str)
    let sd = s.indexOf(search)
    if (sd !== -1) {
      sd += search.length
      let end = s.indexOf(';', sd)
      if (end === -1) {
        end = s.length
      }
      ret = s.substring(sd, end)
    }
  }
  return ret
}

/**
 * 下载文件
 * @param {obj} res 文件api response
 * @returns {byte} 文件
 */
export function downFile (res) {
  if (!res) {
    return
  }
  console.log('size', res.size)
  let filename = getPara(res.headers['Content-disposition'], 'filename')
  console.log('filename', filename)
  if ('msSaveOrOpenBlob' in navigator) {
    // edge和ie的下载方法
    window.navigator.msSaveOrOpenBlob(new Blob([res]))
  } else {
    let url = window.URL.createObjectURL(new Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', 'filename')
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
  }
}
/**
 * 下载文件
 * @param {obj} res 文件api response
 * @returns {byte} 文件
 */
export function openDownloadFile (response) {
  let res = response.data
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(new Blob([res]))
  } else {
    let url = window.URL.createObjectURL(new Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    let fileName = response.headers['filename']
    link.setAttribute('download', decodeURI(fileName))
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
  }
}

// export function downFile (res) {
//   if (!res) {
//     return
//   }
//   let filename = getPara(res.headers['content-disposition'], 'filename')
//   if ('msSaveOrOpenBlob' in navigator) {
//     // edge和ie的下载方法
//     window.navigator.msSaveOrOpenBlob(new Blob([res.data]), filename)
//   } else {
//     let url = window.URL.createObjectURL(new Blob([res.data]))
//     let link = document.createElement('a')
//     link.style.display = 'none'
//     link.href = url
//     link.setAttribute('download', filename)
//     document.body.appendChild(link)
//     link.click()
//     URL.revokeObjectURL(link.href)
//     document.body.removeChild(link)
//   }
// }
